﻿using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using FairyGUI;
using System;

public class LoadingPanel : MonoBehaviour
{
    private int nowProcess;//当前加载进度  
    public static string LoadingScreenSceneName = "LoadingScene";
    public static string _sceneToLoad = "";
    private AsyncOperation async;
    private GComponent view;
    private GLoader bgt;
    void Start()
    {
        LoadingScene();
        UIPackage.AddPackage("Fairy/imcui");
        GObject[] via = GRoot.inst.GetChildren();
        for (int i = 0; i < via.Length; i++)
        {
            ((GObject)via[i]).Dispose();
        }
        view = UIPackage.CreateObject("imcui", "loadingCom").asCom;
        bgt = view.GetChild("bgt").asLoader;
        int index = Convert.ToInt32(_sceneToLoad.Split('_')[1]);
        if (index > 4) {
            index = 1;
        }
        bgt.url = "sence" + index;
        GRoot.inst.AddChild(view);
    }
    void Update()
    {
        if (async == null)
        {
            return;
        }

        int toProcess;
        // async.progress 你正在读取的场景的进度值  0---0.9      
        // 如果当前的进度小于0.9，说明它还没有加载完成，就说明进度条还需要移动      
        // 如果，场景的数据加载完毕，async.progress 的值就会等于0.9    
        if (async.progress < 0.9f)
        {
            toProcess = (int)async.progress * 100;
        }
        else
        {
            toProcess = 100;
        }
        // 如果滑动条的当前进度，小于，当前加载场景的方法返回的进度     
        if (nowProcess < toProcess)
        {
            nowProcess++;
        }

        // 设置为true的时候，如果场景数据加载完毕，就可以自动跳转场景     
        if (nowProcess == 100)
        {
            async.allowSceneActivation = true;         }
    }
    //异步加载scene  
    IEnumerator LoadScene(string sceneToLoad)
    {
        async = SceneManager.LoadSceneAsync(sceneToLoad);
        async.allowSceneActivation = false;
        yield return async;
    }
    public static void LoadSceneAsync(string sceneToLoad)
    {
        _sceneToLoad = sceneToLoad;
        Application.backgroundLoadingPriority = ThreadPriority.High;
        if (LoadingScreenSceneName != null)
        {  
            SceneManager.LoadScene(LoadingScreenSceneName);
        }
    }

    //外部调用的加载的方法  
    public void LoadingScene()
    {
        StartCoroutine("LoadScene", _sceneToLoad);
    }

}